package golang

import (
	"gitee.com/allowall-package/goutil/fn"
)

// 冒泡排序
func BubbleSort(a []int) []int {
	n := len(a)
	for i := 0; i < n; i++ {
		for j := 0; j < n-i-1; j++ {
			if a[j] > a[j+1] {
				a[j], a[j+1] = a[j+1], a[j]
			}
		}
	}

	return a
}

// 冒泡排序优化
func BubbleSort2(a []int) []int {
	n := len(a)
	var f bool

	for i := 0; i < n; i++ {
		f = false

		for j := 0; j < n-i-1; j++ {
			if a[j] > a[j+1] {
				a[j], a[j+1] = a[j+1], a[j]
				f = true
			}
		}

		if !f {
			break
		}
	}

	return a
}

func BubbleSortTest() {
	fn.SliceRand(a)
	s := make([]int, len(a))
	copy(s, a)

	BubbleSort(a)

	fn.Dump(fn.FuncInfo(), s, a)
}
